﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RabbitMQ.Client;
using WebApplication2.Models;

namespace WebApplication2.Common
{
    public class RabbitmqHelper
    {
        public static IConnection _conn;
        public static IModel _channel;

        public static IBasicProperties _properties;
        public IModel CreateConnection()
        {
            if (_conn == null)
            {
                ConnectionFactory factory = new ConnectionFactory
                {
                    UserName = "guest",
                    Password = "guest",
                    HostName = "192.168.0.148"
                };
                _conn = factory.CreateConnection();
            }

            if (_channel == null)
            {
                _channel = _conn.CreateModel();
                _channel.QueueDeclare("orders", false, false, false, null);
                _channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);//告诉broker同一时间只处理一个消息
            }
            if (_properties == null)
            {
                //消息属性
                _properties = _channel.CreateBasicProperties();
                _properties.Persistent = true; //消息持久化
                _properties.Priority = 1; //设置优先级
                _properties.ContentType = ""; //MIME类型
                                              //包含消息头
                IDictionary<string, object> headers = new Dictionary<string, object>();
                headers.Add("localtion", "here");
                headers.Add("time", "today");
                _properties.Headers = headers;
                //消息过期规范
                _properties.Expiration = "60000";
            }
            return _channel;
        }

        public static void SendMessage(Orders order)
        {
            var sendBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(order));
            _channel.BasicPublish("", "orders", false, _properties, sendBytes);
        }
    }
}
